package com.sijia.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sijia.reggie.comment.R;
import com.sijia.reggie.dto.DishDto;
import com.sijia.reggie.entity.Dish;
import com.sijia.reggie.entity.DishFlavor;
import com.sijia.reggie.service.CategoryService;
import com.sijia.reggie.service.DishFlavorService;
import com.sijia.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨思佳
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService ds;

    @Autowired
    private CategoryService cs;

    @Autowired
    private DishFlavorService dfs;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> findPage(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();//页面展示需要用到categoryName，而Dish不含该属性，故使用DishDto
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Dish::getSort);
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        ds.page(dishPage, queryWrapper);
        //对象拷贝，将对Dish表分页查询所得数据(分页信息,不包含所查得数据)拷贝到dishDtoPage
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> records = dishPage.getRecords();
        List<DishDto> list = new ArrayList<>();
        DishDto dishDto = null;
        for (Dish d : records) {
            dishDto = new DishDto();
            BeanUtils.copyProperties(d, dishDto);
            if (cs.getById(d.getCategoryId()) != null) {//根据菜品的分类id查找菜品分类名可能存在查找不到的情况，因此此处的判断避免了空指针异常
                dishDto.setCategoryName(cs.getById(d.getCategoryId()).getName());
            }
            list.add(dishDto);
        }

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }


    /**
     * 新增菜品
     *
     * @param dd
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody DishDto dd) {
        R<String> succeed = ds.saveTwo(dd);
        return succeed;
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @DeleteMapping
    public R<String> deleteBatch(@RequestParam List<Long> ids) {
        ds.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 根据id查询菜品信息以及口味信息
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dishCache", key = "#id", condition = "#id != null")
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        return ds.getTwo(id);
    }


    /**
     * 修改菜品信息和口味信息
     *
     * @param dd
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dd) {
        return ds.updateTwo(dd);
    }


    /**
     * 根据条件（如id）查询菜品信息
     *
     * @param dish
     * @return
     */
    @Cacheable(value = "dishCache", key = "'dish_' + #dish.categoryId + '_' + #dish.status", condition = "#dish != null")
    @GetMapping("/list")
    public R<List<DishDto>> getDish(Dish dish) {
        List<DishDto> dishDtos = null;
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        if (dish.getStatus() != null) {
            queryWrapper.eq(Dish::getStatus, dish.getStatus());
        }
        List<Dish> dishes = ds.list(queryWrapper);

        dishDtos = dishes.stream().map(item -> {
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> flavors = dfs.list(wrapper);
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }


    @CacheEvict(value = "dishCache", allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> changeStatus(@PathVariable int status, Long[] ids) {
        for (long id : ids) {
            Dish d = ds.getById(id);
            d.setStatus(status);
            ds.updateById(d);
        }
        if (status == 0) {
            return R.success("套餐停售成功");
        } else {
            return R.success("套餐起售成功");
        }
    }

}
